package com.jhe.hexed;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class JHexEditorData
{
	private byte[] _bufferData;
	private int _bufferOffset;
	private int _bufferLength;

	public JHexEditorData(byte[] buff)
	{
		_bufferData = buff;
	}

	public int getBufferLength()
	{
		return _bufferLength;
	}

	public void setBufferByte(int offset, byte value)
	{
		_bufferData[_bufferOffset+offset] = value;
	}

	public byte getBufferByte(int offset)
	{
		return _bufferData[_bufferOffset+offset];
	}

	public void setBufferView(int offset, int length)
	{
		_bufferOffset = offset;
		_bufferLength = length;
	}

	public boolean isAtOrigin()
	{
		return _bufferOffset == 0;
	}

	public int find(byte[] values, int fromIndex)
	{
		for (int bufferIndex = fromIndex + _bufferOffset; bufferIndex < _bufferLength; bufferIndex++)
		{
			int valueIndex = 0;
			for (; valueIndex < values.length; valueIndex++)
			{
				if (_bufferData[bufferIndex+valueIndex] != values[valueIndex])
					break;
			}
			if (valueIndex == values.length)
				return bufferIndex - _bufferOffset;
		}
		 
		return -1;
	}

	public void saveToStream(OutputStream file, int start, int end) throws IOException
	{
		file.write(_bufferData, _bufferOffset + start, end - start + 1);
	}

	public void loadFromStream(InputStream file, int pos) throws IOException
	{
		for (int i = pos; i < _bufferLength; i++)
		{
			int ch = file.read();
			if (ch < 0)
				return;
			_bufferData[_bufferOffset+i] = (byte)ch;
		}
	}
}